<?php
/**
 * 前台ajax类
 * @package  ajax
 * @subpackage  shop
 * @create by allen.qiang
 */
quanli_require('module/base/wechatHandler.class.php');
quanli_require('module/base/wechat/wechatCustomer.class.php');
quanli_require('module/base/wechat/wechatArticle.class.php');
quanli_require('module/base/promotionHandler.class.php');

class ajax_display {

    public function execute() {
		
        if( !isset(  $_REQUEST['cmsID'] ) || empty($_REQUEST['cmsID']) || !is_numeric( $_REQUEST['cmsID'] ) ){
            $this->toReturn('参数错误');
        }

        if( !isset(  $_REQUEST['uid'] ) || empty($_REQUEST['uid']) ){
            $this->toReturn('参数错误');
        }

        if (isset($_REQUEST['operFlg']) && is_numeric($_REQUEST['operFlg'])) {

            switch($_REQUEST['operFlg']) {

                case 1: //查询用户条码信息
                    $this->searchBarcode();
                    break;

                case 2: //检查微信互动活动信息并返回会员可参加活动次数
                    $this->searchInteractiveActivities();
                    break;

                case 3: //互动活动抽奖
                    $this->interactiveActivities();
                    break;

                case 4: //检查网点
                    $this->searchMall();
                    break;

                case 5: //检查会员是否参与了门店预购活动
                    $this->searchMallPreorder();
                    break;

                case 6: //提交门店预购
                    $this->submitMallPreorder();
                    break;

                case 7: //查询排期促销信息
                    $this->searchDatePromotion();
                    break;

                case 8: //查询门店信息
                    $this->searchMallInfo();
                    break;

                case 9: //购买促销商品
                    $this->buyPromotonGoods();
                    break;

                default:
                    $this->toReturn( '参数错误' );
                    break;

            }

        } else {
            $this->toReturn( '参数错误' );
        }

    }

    private function submitMallPreorder() {

        if (!isset($_REQUEST['mallCode']) || empty($_REQUEST['mallCode'])) {
            $this->toReturn('参数错误');
        }

        global $G_SHOP;

        $uid = $_REQUEST['uid'];
        $article_id = $_REQUEST['cmsID'];
        $mallCode = $_REQUEST['mallCode'];

        //加载门店类
        quanli_include('module/base/mall/mallBase.class.php');

        //实例门店类
        $mallBase = new mallBase( $G_SHOP->DBCA );

        //实例化微信类
        $wechatHandler = new wechatHandler( $G_SHOP->DBCA );

        //查询门店
        $arg_array = array(
            'mallCode' => $mallCode
        );
        $mall_array = $mallBase->searchMall( $arg_array );
        if (!$mall_array) {
            $this->toReturn('门店没有找到', 404);
        }

        //查询活动
        $active_array = $this->getTemplateCache( $article_id );

        /**
         * ==========================
         * 查询微信会员信息
         * ==========================
         */
        $arg_array = array(
            'uuid' => $uid
        );
        $customer_array = $wechatHandler->searchUserList( $arg_array );
        if ( empty( $customer_array ) ) {
            $this->toReturn('没有找到会员信息' , 404);
        }
        $pcustID = $customer_array[0]['pcustID'];


        //查询活动参与信息
        $promotion_wechat_participation = new entity('promotion_wechat_participation');
        $promotion_wechat_participation->pcustID = $pcustID;
        $promotion_wechat_participation->activeNo = $article_id;
        if ($G_SHOP->DBCA->fetch($promotion_wechat_participation)) {

            if ($promotion_wechat_participation->mallID != $mall_array[0]['mallID']) {
                $this->toReturn('您已参与其他门店活动<br>门店编号：' . $promotion_wechat_participation->mallCode);
            }
            $activity_code = $promotion_wechat_participation->mallCode;

        } else {

            $activity_code = $this->getNumcode( $pcustID, 2 );
            $promotion_wechat_participation->creator = 'system';
            $promotion_wechat_participation->openid = $customer_array[0]['openId'];
            $promotion_wechat_participation->barcode = $activity_code;
            $promotion_wechat_participation->activeType = '05';
            $promotion_wechat_participation->startTime = '2014-02-13 00:00:00';
            $promotion_wechat_participation->endTime = '2014-02-14 23:59:59';
            $promotion_wechat_participation->mallID = $mall_array[0]['mallID'];
            $promotion_wechat_participation->mallCode = $mall_array[0]['mallCode'];
            $G_SHOP->DBCA->save($promotion_wechat_participation);

            quanli_include('module/eai/weixin/wechat.hd.customer.eai.php');

            $params_joinActive_hd = array(
                'openId'	=> $customer_array[0]['openId'],
                'cardId'	=> $pcustID,
                'activityno'=> '05',
                'authcode'	=> $activity_code,
                'begintime' => '2014-02-13 00:00:00',
                'endtime' => '2014-02-14 23:59:59',
                'storecode' => $mall_array[0]['mallCode']
            );
            $wechat_hd_eai = new wechat_hd_eai( $G_SHOP );
            $wechat_hd_eai->joinActivity($params_joinActive_hd);

        }

        $result_array = array(
            'numcode' => $activity_code,
            'info' => array(
                'mallName' => $mall_array[0]['mallName'],
                'mallCode' => $mall_array[0]['mallCode'],
                'provinceName' => $mall_array[0]['provinceName'],
                'cityName' => $mall_array[0]['cityName'],
                'countyName' => $mall_array[0]['countyName'],
                'address' => $mall_array[0]['address'],
                'phone' => $mall_array[0]['phone'],
                'mobile' => $mall_array[0]['mobile']
            )
        );

        $this->toReturn('ok', 200, $result_array);

    }

    /**
     * 检查会员是否参与了门店活动
     */
    private function searchMallPreorder() {

        global $G_SHOP;

        $uid = $_REQUEST['uid'];
        $article_id = $_REQUEST['cmsID'];

        //加载门店类
        quanli_include('module/base/mall/mallBase.class.php');

        //实例门店类
        $mallBase = new mallBase( $G_SHOP->DBCA );

        //实例化微信类
        $wechatHandler = new wechatHandler( $G_SHOP->DBCA );

        //查询活动
        $active_array = $this->getTemplateCache( $article_id );

        /**
         * ==========================
         * 查询微信会员信息
         * ==========================
         */
        $arg_array = array(
            'uuid' => $uid
        );
        $customer_array = $wechatHandler->searchUserList( $arg_array );
        if ( empty( $customer_array ) ) {
            $this->toReturn('没有找到会员信息' , 404);
        }
        $pcustID = $customer_array[0]['pcustID'];

        //查询活动参与信息
        $promotion_wechat_participation = new entity('promotion_wechat_participation');
        $promotion_wechat_participation->pcustID = $pcustID;
        $promotion_wechat_participation->activeNo = $article_id;
        if ($G_SHOP->DBCA->fetch($promotion_wechat_participation)) {

            //查询门店
            $arg_array = array(
                'mallID' => $promotion_wechat_participation->mallID
            );
            $mall_array = $mallBase->searchMall( $arg_array );
            if (!$mall_array) {
                $this->toReturn('ok', 200);
            }

            $result_array = array(
                'numcode' => $promotion_wechat_participation->barcode,
                'info' => array(
                    'mallName' => $mall_array[0]['mallName'],
                    'mallCode' => $mall_array[0]['mallCode'],
                    'provinceName' => $mall_array[0]['provinceName'],
                    'cityName' => $mall_array[0]['cityName'],
                    'countyName' => $mall_array[0]['countyName'],
                    'address' => $mall_array[0]['address'],
                    'phone' => $mall_array[0]['phone'],
                    'mobile' => $mall_array[0]['mobile']
                )
            );

            $this->toReturn('ok', 200, $result_array);

        } else {
            $this->toReturn('ok', 200);
        }

    }

    /**
     * 检查网点并生码
     */
    private function searchMall() {

        if (!isset($_REQUEST['mallCode']) || empty($_REQUEST['mallCode'])) {
            $this->toReturn('参数错误');
        }

        global $G_SHOP;

        $uid = $_REQUEST['uid'];
        $article_id = $_REQUEST['cmsID'];
        $mallCode = $_REQUEST['mallCode'];

        //加载门店类
        quanli_include('module/base/mall/mallBase.class.php');

        //实例门店类
        $mallBase = new mallBase( $G_SHOP->DBCA );

        //查询门店
        $arg_array = array(
            'mallCode' => $mallCode
        );
        $mall_array = $mallBase->searchMall( $arg_array );
        if (!$mall_array) {
            $this->toReturn('门店没有找到', 404);
        }

        $result_array = array(
            'mallCode' => $_REQUEST['mallCode'],
            'info' => array(
                'mallName' => $mall_array[0]['mallName'],
                'mallCode' => $mall_array[0]['mallCode'],
                'provinceName' => $mall_array[0]['provinceName'],
                'cityName' => $mall_array[0]['cityName'],
                'countyName' => $mall_array[0]['countyName'],
                'address' => $mall_array[0]['address'],
                'phone' => $mall_array[0]['phone'],
                'mobile' => $mall_array[0]['mobile']
            )
        );

        $this->toReturn('ok', 200, $result_array);

    }

    /**
     * 互动活动抽奖
     */
    private function interactiveActivities() {
		
        global $G_SHOP;

        $uid = $_REQUEST['uid'];
        $article_id = $_REQUEST['cmsID'];

        //实例化微信管理类
        $wechatHandler = new wechatHandler( $G_SHOP->DBCA );

        //实例促销类
        $promotionHandler = new promotionHandler( $G_SHOP->DBCA );

        /**
         * ==========================
         * 查询微信会员信息
         * ==========================
         */
        $user_array = array(
            'uuid' => $uid
        );
        $customer_array = $wechatHandler->searchUserList( $user_array );
        if ( empty( $customer_array ) ) {
        	
            $this->toReturn('没有找到会员信息' , 404);
        }
        $pcustID = $customer_array[0]['pcustID'];


        /**
         * ==========================
         * 根据模板ID查询活动信息
         * ==========================
         */
        $active_array = $this->getTemplateCache( $article_id );
        if ($active_array['useFlg'] == 0 || $active_array['startDate'] > $G_SHOP->sys_date || $active_array['endDate'] < $G_SHOP->sys_date) {
        	
            $this->toReturn('活动已结束', 404);
        }
        $promotionID = $active_array['promotionID'];




        /**
         * ==========================
         * 查询会员已参加活动的次数
         * ==========================
         */
        $arg_array = array(
            'promotionID' => $promotionID,
            'pcustID' => $pcustID,
            'useDate' => $G_SHOP->sys_date
        );
		
        $active_log_array = $promotionHandler->searchWxActivityLog( $arg_array );
        
        if ($active_log_array) {
            if ($active_array['participateTime'] <= count($active_log_array)) {
                if (isset($_REQUEST['activeType']) && $_REQUEST['activeType'] == 9) {
                    $this->toReturn('您今天的盖高楼次数已用完', 404);
                } else {
                    $this->toReturn('您今天的抽奖次数已用完', 404);
                }
            }
        }


        /**
         * 查询促销活动奖项
         */
        $arg_array = array(
            'promotionID' => $promotionID
        );
        $option_array = $promotionHandler->searchWxActivityDetail( $arg_array );
        if (!$option_array) {
        	
            $this->toReturn('很抱歉，您没有中奖', 404);
        }

        $data_array = null;

        /**
         * ======================================
         * 生成随机数，判断会员是否中奖
         * ======================================
         */
        foreach($option_array as $option) {

            if ($option['alreadyGetNum'] >= $option['prizeNum']) {
                continue;
            }


            //查询奖项中奖号码
            $arg_array = array(
                'awardsID' => $option['awardsID']
            );
            $awards_num_array = $promotionHandler->searchWxActivityAwardsRandom( $arg_array );

            //生成中奖号码
            $randNum = mt_rand(10000, 10000 + $option['awardsRate']);
//            $randNum = 10626;
//            $randNum = 10263;//摇一摇中奖码

            //判断新生成的中奖号码是否在奖项中奖号码中
            if (in_array($randNum, $awards_num_array)) {

                //更新奖项中奖数据
                $update_sql = 'UPDATE promotion_weixin_detail SET alreadyGetNum = alreadyGetNum + 1 WHERE awardsID = ? AND prizeNum > alreadyGetNum';
                if ($G_SHOP->DBCA->stmt_query( $update_sql, 'i', $option['awardsID'] )) {

                    //保存中奖记录
                    $option['pcustID'] = $pcustID;
                    $option['prize_num'] = $randNum;
                    $promotionHandler->saveCustomerWxPrize( $option );

                    $data_array = $option;
                    break;

                }

            }

        }

        //保存领取记录
        $arg_array = array(
            'promotionID' => $promotionID,
            'pcustID' => $pcustID,
            'useDate' => $G_SHOP->sys_date,
        );

        $promotionHandler->saveWxActivityLog( $arg_array );

        //保存盖高楼记录
        if ($active_array['activeType'] == 9) {
            $search_sql = sprintf('SELECT IF(MAX(%s) IS NULL ,1 , MAX(%s)+1) AS max_sort FROM %s ', 'gglNum', 'gglNum', 'promotion_weixin_ggl');

            $sort_array = $G_SHOP->DBCA->stmt_query($search_sql);

            $arg_array = array(
                'gglNum' => $sort_array[0]->max_sort,
                'promotionID' => $promotionID,
                'pcustID' => $pcustID,
                'message' => $_REQUEST['ebsig_message'],
                'gglDate'=>date('Y-m-d')
            );
            $promotionHandler->saveGglActivity($arg_array);
        }
		
        $this->toReturn('ok', 200, $data_array);

    }

    /**
     * 检查微信互动活动信息并返回会员可参加活动次数
     */
    private function searchInteractiveActivities() {
		
        global $G_SHOP;

        $uid = $_REQUEST['uid'];
        $article_id = $_REQUEST['cmsID'];

        //实例化微信管理类
        $wechatHandler = new wechatHandler( $G_SHOP->DBCA );

        //实例促销类
        $promotionHandler = new promotionHandler( $G_SHOP->DBCA );

        /**
         * ==========================
         * 查询微信会员信息
         * ==========================
         */
        $user_array = array(
            'uuid' => $uid
        );
        $customer_array = $wechatHandler->searchUserList( $user_array );
        if ( empty( $customer_array ) ) {
            $this->toReturn('没有找到会员信息' , 404);
        }
        $pcustID = $customer_array[0]['pcustID'];
        /**
         * ==========================
         * 查询微信会员信息
         * ==========================
         */



        /**
         * ==========================
         * 根据模板ID查询活动信息
         * ==========================
         */
        $active_array = $this->getTemplateCache( $article_id );
        
        /**
         * ==========================
         * 根据模板ID查询活动信息
         * ==========================
         */

        //返回数据
        $result_array = array();

        /**
         * ==========================
         * 判断活动是否已禁用、已过期、未开始等状态
         * 查询会员已参加活动的次数，并得到可参加活动次数
         * ==========================
         */
        if ($active_array['useFlg'] == 0 || $active_array['startDate'] > $G_SHOP->sys_date || $active_array['endDate'] < $G_SHOP->sys_date) {
            $result_array['num'] = 0;

        } else {

            //查询今日参与记录
            $arg_array = array(
                'promotionID' => $active_array['promotionID'],
                'pcustID' => $pcustID,
                'useDate' => $G_SHOP->sys_date
            );
            $active_log_today_array = $promotionHandler->searchWxActivityLog( $arg_array );

            //查询总参与记录
            $arg_array = array(
                'promotionID' => $active_array['promotionID'],
                'pcustID' => $pcustID
            );
            $active_log_total_array = $promotionHandler->searchWxActivityLog( $arg_array );

            //如果每日最多参与次数没有限制，则跟总参与数对比
            if( $active_array['participateTime'] == 0 ){

                $result_array['num'] = $active_array['totalTime'] - count($active_log_total_array);
                if ($result_array['num'] < 0) {
                    $result_array['num'] = 0;
                }

            } else {  //如果每日最多参与次数有限制，则跟"每日可参加的次数"对比

                $result_array['num'] = $active_array['participateTime'] - count($active_log_today_array);
                if ($result_array['num'] < 0) {
                    $result_array['num'] = 0;
                }

            }

        }
        /**
         * ==========================
         * 判断活动是否已禁用、已过期、未开始等状态
         * 查询会员已参加活动的次数，并得到可参加活动次数
         * ==========================
         */



        /**
         * ==========================
         * 查询会员未领取的奖品
         * ==========================
         */
        $arg_array = array(
            'pcustID' => $pcustID,
            'isReceive' => 0
        );
        $cust_award_array = $promotionHandler->searchCustomerWxPrize( $arg_array );
        if ($cust_award_array) {
            $result_array['cust_award_count'] = count($cust_award_array);
        } else {
            $result_array['cust_award_count'] = 0;
        }
        /**
         * ==========================
         * 查询会员未领取的奖品
         * ==========================
         */

        /**
         * =========================
         * 盖高楼
         * =========================
         */
        if($active_array['activeType'] == 9){
            $ggl_arr = array(
                'sortname'=>'gglNum',
                'sortorder'=>'desc',
                'page'=>1,
                'rp'=>10
            );
            $result_array['ggl'] = $promotionHandler->searchGglActivity($ggl_arr);
        }

        /**
         * =========================
         * 盖高楼
         * =========================
         */
        
        $this->toReturn('ok', 200, $result_array);

    }

    /**
     * 查询用户条码信息
     */
    private function searchBarcode() {

        global $G_SHOP;


        $uid = $_REQUEST['uid']; //会员uuid
        $article_id = $_REQUEST['cmsID']; //模板ID


        //检查是否已生成数字码
        $barcode = $G_SHOP->sessionCache_get('BARCODE_' . $uid . $article_id, true);
        $barcode = '';
        if ($barcode) {
            $G_SHOP->set_cookie_info('BARCODE_' . $uid . $article_id, $barcode, 604800);
            $this->toReturn('ok', 200, $barcode);
        }


        //实例微信会员类
        $wechatCustomer = new wechatCustomer( $G_SHOP->DBCA );
        //实例微信模板类
        $wechatArticle = new wechatArticle( $G_SHOP->DBCA );


        //查询微信用户信息
        $arg_array = array(
            'uuid' => $uid
        );
        $customer_array = $wechatCustomer->searchCustomer( $arg_array );
        if ( empty( $customer_array ) ) {
            $this->toReturn('会员信息没有找到' , 404);
        }
        $customer_array = $customer_array[0];


        //查询模板信息
        $arg_array = array(
            'article_id' => $article_id
        );
        $article_array = $wechatArticle->searchArticle( $arg_array );
        if ( empty($article_array) ) {
            $this->toReturn('模板信息没有找到' , 404);
        }
        $article_array = $article_array[0];

        if ( $article_array['code_type'] ) {

            //查询用户是否已经参与活动
            $wechat_participation = new entity('wechat_participation');
            $wechat_participation->pcustID = $customer_array['pcustID'];
            $wechat_participation->activeNo = $article_id;
            if ( !$G_SHOP->DBCA->fetch($wechat_participation) ) {

                /**
                 * 生成条码
                 */
                if ($article_array['activeType'] == 7) { //通关密语
                    $barcode = $customer_array['pcustID'] . '01'; //数字码生成（会员号+01）
                    $external_no = '01';
                    $activityType = 1;
                } else { //x元购
                    $barcode = $this->getNumcode( $customer_array['pcustID'] );
                    if ($barcode == 0) {
                        $this->toReturn('亲，生码失败鸟！<br>请关闭页面重新打开！tks！');
                    }
                    $external_no = '02';
                    $activityType = 2;
                }

                //保存微信活动参与记录
                $wechat_participation->creator = 'system_participation_auto';
                $wechat_participation->openid = $customer_array['openId'];
                $wechat_participation->barcode = $barcode;
                $wechat_participation->external_no = $external_no;
                $wechat_participation->createDate = $G_SHOP->sys_date;
                $wechat_participation->activityType = $activityType;
                $wechat_participation->startTime = $article_array['use_startDate'];
                $wechat_participation->endTime = $article_array['use_endDate'];
                $G_SHOP->DBCA->save( $wechat_participation );

                //加载异步同类
                quanli_include('module/base/common/ebsigAsync.class.php');

                //实例异步通知类
                $ebsigAsync = new ebsigAsync();

                //异步通知调用第三方接口
                $ebsigAsync->callbackUrl = G_WEBSITE_DOMAINNAME . '/api/async/wechat.code.php';
                $params['uuid'] = $wechat_participation->uuid;
                $ebsigAsync->push( $params );

                //生码类型
                $code_type_array = explode(',', $article_array['code_type']);

                //一维码，生成一维码图片
                if (in_array(1, $code_type_array)) {

                    //加载条形码类
                    quanli_include('module/base/common/quanliBarcode.class.php');

                    //实例条码类
                    $quanliBarcode = new quanliBarcode();

                    //生成条码
                    $quanliBarcode->create($barcode);

                }

                //二维码，生成二维码图片
                if (in_array(2, $code_type_array)) {

                    //加载二维码类
                    quanli_include('module/base/common/quanliQrcode.class.php');

                    //实例二维码类
                    $quanliQrcode = new quanliQrcode();

                    //生成二维码
                    $quanliQrcode->create($barcode);

                }

            } else {

                $barcode = $wechat_participation->barcode;

            }

        }

        if ($barcode) {
            $G_SHOP->sessionCache_set('BARCODE_' . $uid . $article_id, $barcode, 604800, true);
            $G_SHOP->set_cookie_info('BARCODE_' . $uid . $article_id, $barcode);
        }

        $this->toReturn('ok', 200, $barcode);

    }

    /**
     * 查询模板缓存信息（包括预约活动和互动活动）
     * @param $article_id
     * @return array|mixed
     */
    private function getTemplateCache( $article_id ) {

        global $G_SHOP;

        $active_array = $G_SHOP->sessionCache_get('TEMPLATE_' . $article_id, true);
        /*if ($active_array) {
            return $active_array;
        }*/

        //实例化微信管理类
        $wechatHandler = new wechatHandler( $G_SHOP->DBCA );

        //查询模板并判断模板状态
        $cms_array = array(
            'article_id' => $article_id
        );
        $article_array = $wechatHandler->searchArticle( $cms_array );
        if (!$article_array) {
            $this->toReturn('模板信息没有找到', 404);
        }
        $article_array = $article_array[0];

        if ($article_array['activeType'] == 2) { //预约活动

            //生成预约活动数组
            $active_array = array(
                'activeType' => $article_array['activeType'],
                'code_type' => $article_array['code_type'],
                'code_startDate' => $article_array['code_startDate'],
                'code_endDate' => $article_array['code_endDate'],
                'use_startDate' => $article_array['use_startDate'],
                'use_endDate' => $article_array['use_endDate'],
                'limit_num' => $article_array['limit_num'],
                'useType' => $article_array['useType'],
                'useTime' => $article_array['useTime']
            );

        } else if (in_array($article_array['activeType'],array(1,5,9,10))) { //互动活动

            //实例化促销类
            $promotionHandler = new promotionHandler( $G_SHOP->DBCA );

            //查询活动信息
            $arg_array = array(
                'promotionID' => $article_array['promotionID']
            );
            $wechat_active_array = $promotionHandler->searchWxActivity( $arg_array );
            if (!$wechat_active_array) {
                $this->toReturn('暂无正在进行的活动', 404);
            }
            $wechat_active_array = $wechat_active_array[0];

            //互动活动数组
            $active_array = array(
                'promotionID' => $article_array['promotionID'],
                'activeType' => $article_array['activeType'],
                'promotionType' => $wechat_active_array['promotionType'],
                'startDate' => $wechat_active_array['startDate'],
                'endDate' => $wechat_active_array['endDate'],
                'useFlg' => $wechat_active_array['useFlg'],
                'participateTime' => $wechat_active_array['participateTime'],
                'isPointsExchange' => $wechat_active_array['isPointsExchange'],
                'points' => $wechat_active_array['points'],
                'maxExchangeTime' => $wechat_active_array['maxExchangeTime']
            );

        }

        $G_SHOP->sessionCache_set('TEMPLATE_' . $article_id, $active_array, 86400, true);

        return $active_array;

    }

    /**
     * ajax返回信息
     * @param string $msg 信息
     * @param int $code 代码
     * @param mixed $data 返回的数据
     */
    private function toReturn( $msg, $code = 400, $data='' ) {

        die( json_encode( array( 'code' => $code, 'message' => $msg, 'data' => $data ) ) );

    }

    /**
     * 生成数字码（也是条形码和二维码的内容）
     * @param int $pcustID 会员号
     * @param int $rule 生码规则（1.会员号倒数第二位插入一个0-9的数字、最后一次查询一个2-9的数字；2.会员号后插5位随机数）
     * @return bool|string
     */
    private function getNumcode( $pcustID, $rule=1 ) {

    	global $G_SHOP;

        //最多生成100次数字码
    	for ($i=0; $i<100; $i++) {

            //生成数字码
            if ($rule == 1) {
                $numCode = substr($pcustID, 0, 6) . mt_rand(0,9) . substr($pcustID, -1) . mt_rand(2, 9);
            } else {
                $numCode = $pcustID . mt_rand(10000, 99999);
            }

            //查询活动参数记录
    		$sql_get_barcode = 'SELECT barcode FROM wechat_participation WHERE barcode = ?';
    		$barcode_exists_result = &$G_SHOP->DBCA->stmt_query($sql_get_barcode, 'i', $numCode);

            //如果数字码不存在，则返回
    		if (!$barcode_exists_result) {
    			return $numCode;
    		}

    	}
    	
    	return 0;

    }

    function searchDatePromotion(){

        global $G_SHOP;

        $uid = $_REQUEST['uid'];
        $article_id = $_REQUEST['cmsID'];

        //返回信息数组
        $return_array = array(
            'promotionID' => 0,         //促销ID
            'mapID' => 0,               //排期ID
            'isActivity' => 0,         //促销活动状态：1.未开始   2.进行中   3.已结束
            'is_participation' => 0,  //是否重复参与促销活动标志
            'barcode' => '',           //参与活动后生成的条码
            'mapDetail' => array(),   //排期促销详情（如果是商品促销，则为多个促销商品组成的数组）
            'mapInfo' => array(),     //排期信息
            'mallInfo' => array()     //门店信息
        );

        //加载门店类
        quanli_include('module/base/mall/mallBase.class.php');

        //实例门店类
        $mallBase = new mallBase( $G_SHOP->DBCA );

        //实例化微信类
        $wechatHandler = new wechatHandler( $G_SHOP->DBCA );

        //实例化促销类
        $promotionHandler = new promotionHandler( $G_SHOP->DBCA );

        /**
         * ==========================
         * 查询微信会员信息
         * ==========================
         */
        $arg_array = array(
            'uuid' => $uid
        );
        $customer_array = $wechatHandler->searchUserList( $arg_array );
        if ( empty( $customer_array ) ) {
            $this->toReturn('没有找到会员信息');
        }
        $pcustID = $customer_array[0]['pcustID'];

        //获取当前日期
        $curTime = '\''.date('Y-m-d H:i:s').'\'';
        $currentTime = date('Y-m-d H:i:s');

        //查询活动
        $search_array = array(
            'extendSql' => ' AND endTime >= '.$curTime
        );
        $promotion_array = $promotionHandler->searchDatePromotionMap( $search_array );

        if( empty($promotion_array) ){
            $this->toReturn('活动未开始，请耐心等候');
        }

        //根据“预约时间”判断
        if( $promotion_array[0]['order_startTime'] > $currentTime ){  //活动未开始
            $return_array['isActivity'] = 1;
        } else if ( $promotion_array[0]['order_endTime'] < $currentTime ){  //活动已结束
            $return_array['isActivity'] = 3;
        } else {  //活动进行中
            $return_array['isActivity'] = 2;
        }

        //记录排期信息
        $return_array['mapInfo'] = $promotion_array[0];

        $return_array['promotionID'] = $promotion_array[0]['promotionID'];
        $return_array['mapID']        = $promotion_array[0]['mapID'];

        //查询促销详细信息
        $search_map_detail = array(
            'mapID' => $promotion_array[0]['mapID']
        );
        $promotion_map_detail = $promotionHandler->searchDatePromotionDetail( $search_map_detail );

        if( empty($promotion_map_detail) ){
            $this->toReturn('活动商品已抢光，请继续关注我们后期的活动');
        }

        $return_array['mapDetail'] = $promotion_map_detail;

        //查询用户参与促销记录信息
        $arg_array = array(
            'pcustID' => $pcustID,
            'mapID' => $promotion_array[0]['mapID']
        );
        $promotion_participation = $promotionHandler->searchDatePromotionBuyLog($arg_array);

        //如果促销活动“不可重复参与”，则查询出该会员的参与记录
        if( $promotion_participation && $promotion_array[0]['isRepeat'] == 2 ){

            $return_array['is_participation'] = 1;

            $return_array['barcode'] = $promotion_participation[0]['barcode'];

            //查询选购的商品信息
            $search_goods_array = array(
                'mapID'  => $promotion_participation[0]['mapID'],
                'postID' => $promotion_participation[0]['postID']
            );
            $buy_goods = $promotionHandler->searchDatePromotionDetail($search_goods_array);
            $return_array['mapDetail'] = $buy_goods[0];

            //查询门店
            $arg_array = array(
                'mallCode' => $promotion_participation[0]['mallCode']
            );
            $mall_array = $mallBase->searchMall( $arg_array );

            $return_array['mallInfo'] = $mall_array[0];

            $this->toReturn('ok',200,$return_array);
        }

        $this->toReturn('ok',200,$return_array);

    }

    //查询门店信息
    private function searchMallInfo(){

        if (!isset($_REQUEST['mallCode']) || empty($_REQUEST['mallCode'])) {
            $this->toReturn('参数错误');
        }

        global $G_SHOP;

        $mallCode = $_REQUEST['mallCode'];

        //加载门店类
        quanli_include('module/base/mall/mallBase.class.php');

        //实例门店类
        $mallBase = new mallBase( $G_SHOP->DBCA );

        //查询门店
        $arg_array = array(
            'mallCode' => $mallCode
        );
        $mall_array = $mallBase->searchMall( $arg_array );
        if (!$mall_array) {
            $this->toReturn('门店没有找到', 404);
        }

        $this->toReturn('ok', 200 , $mall_array[0]);

    }

    //购买促销商品
    private function buyPromotonGoods(){

        if (!isset($_REQUEST['mallCode']) || !isset($_REQUEST['postID']) || !isset($_REQUEST['mapID']) || !isset($_REQUEST['promotionID']) ) {
            $this->toReturn('参数错误');
        }

        if( empty( $_REQUEST['mallCode'] ) || !is_numeric($_REQUEST['postID']) || !is_numeric($_REQUEST['mapID']) || !is_numeric($_REQUEST['promotionID']) ){
            $this->toReturn('参数错误');
        }

        global $G_SHOP;

        $mallCode    =  $_REQUEST['mallCode'];
        $postID      =  $_REQUEST['postID'];
        $uid         = $_REQUEST['uid'];
        $article_id  = $_REQUEST['cmsID'];
        $mapID       = $_REQUEST['mapID'];
        $promotionID = $_REQUEST['promotionID'];

        //返回数组
        $return_array = array(
            'mallinfo' => array(),
            'mapinfo' => array(),
            'mapdetail' => array(),
            'barcode' => '',
            'goodsInfo' => array()
        );

        //加载门店类
        quanli_include('module/base/mall/mallBase.class.php');

        //实例门店类
        $mallBase = new mallBase( $G_SHOP->DBCA );

        //实例化商品类
        $goodsHandler = new goodsHandler( $G_SHOP->DBCA );

        //实例化微信类
        $wechatHandler = new wechatHandler( $G_SHOP->DBCA );

        //实例促销类
        $promotionHandler = new promotionHandler( $G_SHOP->DBCA );

        /**
         * ==========================
         * 查询微信会员信息
         * ==========================
         */
        $arg_array = array(
            'uuid' => $uid
        );
        $customer_array = $wechatHandler->searchUserList( $arg_array );
        if ( empty( $customer_array ) ) {
            $this->toReturn('没有找到会员信息');
        }

        $goodsInfo = $goodsHandler->searchGoodsSale($_REQUEST);

        if( !$goodsInfo ){
            $this->toReturn('商品没有找到', 404);
        }

        //查询商品外部编码
        $search_goods_code_sql = 'SELECT * FROM goods_code WHERE postID=?';
        $goods_code            = $G_SHOP->DBCA->stmt_query( $search_goods_code_sql , 'i' , $postID );

        //记录商品信息
        $return_array['goodsInfo'] = $goodsInfo;

        //查询门店
        $arg_array = array(
            'mallCode' => $mallCode
        );
        $mall_array = $mallBase->searchMall( $arg_array );
        if (!$mall_array) {
            $this->toReturn('门店没有找到', 404);
        }

        //记录门店信息
        $return_array['mallinfo'] = $mall_array[0];

        //获取活动条码
        $acticityCode = $this->getPromotionCode($customer_array[0]['pcustID'],1);

        $return_array['barcode'] = $acticityCode;

        //查询排期信息
        $search_map_array = array(
            'mapID' => $mapID
        );
        $mapInfo = $promotionHandler->searchDatePromotionMap($search_map_array);

        if( !$mapInfo ){
            $this->toReturn('没有找到促销信息');
        }

        $return_array['mapinfo'] = $mapInfo[0];

        try{

            //开启事务
            $G_SHOP->DBCA->beginTransaction();

            //更新排期详情数据
            $promotion_wx_datapromotion_detail = new entity('promotion_wx_datapromotion_detail');
            $promotion_wx_datapromotion_detail->mapID = $mapID;
            $promotion_wx_datapromotion_detail->postID = $postID;

            if( !$G_SHOP->DBCA->fetch( $promotion_wx_datapromotion_detail ) ){
                throw new Exception( '没有找到促销商品信息' , 400 );
            }

            //更新“已购买数量”
            $promotion_wx_datapromotion_detail->buyCount = $promotion_wx_datapromotion_detail->buyCount+1;
            $G_SHOP->DBCA->save($promotion_wx_datapromotion_detail);

            //查询是否已经超卖
            $check_array = array(
                'mapID' => $mapID,
                'postID' => $postID
            );
            $check_result = $promotionHandler->searchDatePromotionDetail($check_array);

            if( $check_result[0]['buyCount'] > $check_result[0]['goodsCount'] ){
                throw new Exception( '商品库存不足' , 400 );
            }

            $return_array['mapdetail'] = $check_result[0];

            //保存用户参与记录
            $save_array = array(
                'operator' => $customer_array[0]['pcustID'],
                'promotionID' => $promotionID,
                'mapID' => $mapID,
                'openid' => $customer_array[0]['openId'],
                'pcustID' => $customer_array[0]['pcustID'],
                'mallCode' => $mallCode,
                'barcode' =>  $acticityCode,
                'postID' =>  $postID,
                'extend_3' =>  $_REQUEST['mobile']
            );

            $save_promotion_log = $promotionHandler->saveDatePromotionBuyLog($save_array);

            if( $save_promotion_log['code'] != 200 ){
                throw new Exception( '系统繁忙，请稍候再试' , 400 );
            }

            quanli_include('module/eai/weixin/wechat.hd.customer.eai.php');

            $params_joinActive_hd = array(
                'openId'	=> $customer_array[0]['openId'],
                'cardId'	=> $customer_array[0]['pcustID'],
                'activityno'=> $goods_code[0]->goodsCode,
                'authcode'	=> $acticityCode,
                'begintime' => $mapInfo[0]['startTime'],
                'endtime' => $mapInfo[0]['endTime'],
                'storecode' => $mall_array[0]['mallCode']
            );
            $wechat_hd_eai = new wechat_hd_eai( $G_SHOP );
            $wechat_hd_eai->joinActivity($params_joinActive_hd);

            //提交事务
            $G_SHOP->DBCA->commit();

            $this->toReturn('ok',200,$return_array);

        }catch (Exception $e){

            //回滚事务
            $G_SHOP->DBCA->rollBack();

            if( $e->getCode() > 0 ){
                $this->toReturn($e->getMessage());
            } else {
                error_log( $e->getMessage() );
                $this->toReturn('系统错误，保存失败',500);
            }

        }

    }

    /**
     * 生成微信促销数字码（也是条形码和二维码的内容）
     * @param int $pcustID 会员号
     * @param int $rule 生码规则（1.会员号倒数第二位插入一个0-9的数字、最后一次查询一个2-9的数字；2.会员号后插5位随机数）
     * @return bool|string
     */
    private function getPromotionCode( $pcustID, $rule=1 ) {

        global $G_SHOP;

        //最多生成100次数字码
        for ($i=0; $i<100; $i++) {

            //生成数字码
            if ($rule == 1) {
                $numCode = substr($pcustID, 0, 5) . mt_rand(0,9) . substr($pcustID, -1) . mt_rand(2, 9) . substr($pcustID, -2 , 1);
            } else {
                $numCode = $pcustID . mt_rand(10000, 99999);
            }

            //查询活动参数记录
            $sql_get_barcode = 'SELECT barcode FROM promotion_wx_datepromotion_buylog WHERE barcode=?';
            $barcode_exists_result = $G_SHOP->DBCA->stmt_query($sql_get_barcode, 'i', $numCode);

            //如果数字码不存在，则返回
            if (!$barcode_exists_result) {
                return $numCode;
            }

        }

        return false;

    }
    
}